<script setup lang="ts">
import { readDirURL, createURL, deleteURL, downloadURL, writeFileURL } from '@/api';

import type { File as FileInfo, TableHeader } from '@/types/fs';

const tableHeaders: TableHeader[] = [
  { title: "文档名称", key: "filename" },
  { title: "存储节点", key: "domain" },
  { title: "修改时间", key: "modifiedAt" },
  { title: "大小", key: "size" },
];

const usePath = () => {
  const route = useRoute();
  const path = computed(() =>
    [''].concat(route.params.slug ? (route.params.slug as string[]) : [])
  );

  return { path };
};

const useBreadcrumbs = () => {
  const { path } = usePath();

  const breadcrumbsItems = computed(() => {
    const items = path.value.map((v, i) => ({
      title: v ? v : '/',
      disabled: false,
      to: `/fs/file${path.value.slice(0, i + 1).join('/')}`,
    }));
    return items;
  });

  return { breadcrumbsItems };
};

const useTableData = async () => {
  const { path } = usePath();
  const url = computed(() => `${readDirURL}${path.value.join('/')}`);

  const { data, refresh } = await useFetch<FileInfo[]>(url);

  return {
    data: data,
    items: computed( () =>
      data?.value
        ?.map((v) => ({
          filename: v.filename,
          modifiedAt: "-",
          size: transformSize2HumanReadable(v.size),
          isDir: v.is_dir,
          domain: v.domain,
        }))
        .sort((x, y) => {
          if (x.isDir && !y.isDir) {
            return -1;
          }
          if (!x.isDir && y.isDir) {
            return 1;
          }

          return 0;
        })
    ),
    refresh: async () => await refresh(),
  };
};

const uploadFiles = ref<File[] | null>(null);
const uploadFile = async () => {
  uploadFiles.value?.forEach(async (file) => {
    const reqBody = computed(() => ({
      filename: file.name,
      is_dir: false,
    }));
    await $fetch(
      `${createURL}${path.value.join('/')}`, 
      { 
        method: 'POST', 
        body: reqBody.value 
      }
    );

    const formdata = new FormData();
    formdata.append('file', file);
    await $fetch(
      `${writeFileURL}${path.value.join('/')}/${file.name}`, 
      { 
        method: 'POST', 
        body: formdata 
      }
    );
    await refresh();
  });
};

const deleteFile = async () => {
  const url = computed(() => `${deleteURL}`);

  selectData.value.forEach(async (v) => {
    const reqBody = computed(() => ({
      path: path.value.concat(v.filename).join('/'),
    }));
    await $fetch(url.value, { method: 'POST', body: reqBody.value })
    await refresh()
  });

  selectIDs.value = [];
};

const downloadFile = async () => {
  const downloadFiles = selectData.value.filter((v) => !v.isDir);
  downloadFiles.forEach((v) => {
    const a = document.createElement('a');
    a.href = `${downloadURL}${path.value.join('/')}/${v.filename}`;
    a.download = v.filename;
    a.click();
  });
};

const useCreateDirectory = async (refresh: () => Promise<void>) => {
  const dialogActive = ref(false);
  const directoryName = ref('');

  const { path } = usePath();
  const url = computed(() => `${createURL}${path.value.join('/')}`);
  const reqBody = computed(() => ({
    filename: directoryName.value,
    is_dir: true,
  }));

  const openDialog = () => {
    dialogActive.value = true;
  };

  const closeDialog = () => {
    dialogActive.value = false;
  };

  const createDirectory = async () => {
    await $fetch(url.value, { method: 'POST', body: reqBody.value });
    await refresh();
    closeDialog();
    directoryName.value = '';
  };

  return {
    dialogActive,
    directoryName,
    openDialog,
    closeDialog,
    createDirectory,
  };
};

const { path } = usePath();
const { breadcrumbsItems } = useBreadcrumbs();
const { data, refresh, items: tableItems } = await useTableData();
const selectIDs = ref<string[]>([]);
const selectData = computed(() => {
    const items = ref<FileInfo[]>([]);
      data?.value?.forEach((v) => {
      if (selectIDs.value.includes(v.filename)) {
        items.value.push(v);
      }
    });
    return items.value;  
  }
);

const {
  dialogActive,
  directoryName,
  openDialog,
  closeDialog,
  createDirectory,
} = await useCreateDirectory(refresh);

const search = ref('');
</script>

<template>
  <div>
    <v-row class="align-center" justify="start" no-gutters>
      <div v-if="path.length > 1">
        <NuxtLink :to="`/fs/file${path.slice(0, -1).join('/')}`">
          <v-icon icon="mdi-arrow-up" />
        </NuxtLink>
      </div>

      <div v-else>
        <v-icon color="grey" icon="mdi-arrow-up" />
      </div>

      <span class="ml-4"> 当前文件夹路径： </span>

      <v-breadcrumbs :items="breadcrumbsItems">
        <template #divider>
          <v-icon icon="mdi-chevron-right" />
        </template>

        <template #title="{ item }">
          <NuxtLink :to="item.href">{{ item.title }}</NuxtLink>
        </template>
      </v-breadcrumbs>
    </v-row>

    <v-row no-gutters>
      <v-col>
        <div v-if = "selectIDs.length === 0">
          <v-btn 
            text="新建文件夹"
            prepend-icon="mdi-folder-plus"
            color="primary"
            @click="openDialog"
          />
          <!-- <v-file-input 
            v-model="uploadFiles"
            label="上传文件" 
            multiple
            show-size
            rounded
          /> -->
        </div>
        <div v-else>
          <v-btn 
            text="删除"
            prepend-icon="mdi-delete"
            @click="deleteFile"
          /> 
          <v-btn 
            class="ml-2"
            prepend-icon="mdi-download"
            text="下载"
            @click="downloadFile"
          /> 
        </div>
      </v-col>

      <v-spacer />

      <v-col cols="4">
        <v-text-field
          v-model="search"
          density="compact"
          label="输入搜索关键词"
          prepend-inner-icon="mdi-magnify"
          variant="solo-filled"
          flat
          hide-details
          single-line
        />
      </v-col>
    </v-row>

    <v-data-table
      v-model="selectIDs"
      v-model:search="search"
      :headers="tableHeaders"
      :items="tableItems"
      item-value="filename"
      show-select
    >
      <template #item.filename="{ item }">
        <div v-if="item.isDir">
          <NuxtLink :to="`/fs/file${path.join('/')}/${item.filename}`">
            <div class="flex items-center">
              <div class="mr-2">
                <v-icon color="blue" icon="mdi-folder" />
              </div>
              <span>
                {{ item.filename }}
              </span>
            </div>
          </NuxtLink>
        </div>

        <div v-else class="flex items-center">
          <div class="mr-2">
            <v-icon icon="mdi-file" />
          </div>
          <span>
            {{ item.filename }}
          </span>
        </div>
      </template>

      <template #item.size="{ item }">
        <div v-if="item.isDir">-</div>
        <div v-else>
          {{ item.size }}
        </div>
      </template>

      <template #item.domain="{ item }">
        <v-chip v-if="item.domain.startsWith('云')" :text="item.domain" color="blue" />
        <v-chip v-else-if="item.domain.startsWith('边')" :text="item.domain" color="green" />
        <v-chip v-else-if="item.domain.startsWith('端')" :text="item.domain" color="orange" />
      </template>
    </v-data-table>

    <v-dialog v-model="dialogActive" max-width="500">
      <v-card rounded="lg">
        <v-card-text>
          <v-text-field
            v-model="directoryName"
            density="compact"
            label="输入文件夹名称"
            variant="solo-filled"
            flat
            hide-details
            single-line
          />
        </v-card-text>
        <div class="d-flex justify-end">
          <v-btn color="primary mr-2" text="确认" @click="createDirectory" />
          <v-btn class="text-none mr-6 mb-4" text="取消" @click="closeDialog" />
        </div>
      </v-card>
    </v-dialog>
    <div 
      v-if = "uploadFiles"
      @click="uploadFile()"
    >
      {{ uploadFiles[0].name}}
     </div>
  </div>
</template>
